//
//  LGBreathRecordController.m
//  HeartDisease_YHJK
//
//  Created by 1234 on 2025/8/6.
//  呼吸训练记录

#import "LGBreathRecordController.h"
//统计图
#import "LGBreathRecordChartController.h"
//报告
#import "LGBreathRecordDetailController.h"
#import "LGBreathRecordCell.h"
#import "DatePickerTwoView.h"
@interface LGBreathRecordController ()<DatePickerViewDelegate,UITableViewDelegate,UITableViewDataSource>
/**   */
@property (nonatomic , strong)UITableView *tableView;
@property (nonatomic , strong)UITextField *startItem;
@property (nonatomic , strong)UITextField *endItem;
/**  汇总数据 */
@property (nonatomic , strong)UIButton *chartBtn;
@property (nonatomic , copy)NSString *startDate;
@property (nonatomic , copy)NSString *endDate;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
@end

@implementation LGBreathRecordController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"呼吸训练统计";
    [self.view addSubview:self.chartBtn];
    [self.view addSubview:self.startItem];
    [self.view addSubview:self.endItem];
    [self.view addSubview:self.tableView];
    [self emptyViewWithSuperView:self.view frame:self.tableView.frame];
    self.emptyView.backgroundColor = [UIColor clearColor];
    [self initRequestDate];
    [self requestData];
}


-(void)requestData{
    [RequestUtil withPOST:@"/doctor/patient.Physicalsign/pranayamaList" parameters:@{@"patient_id":self.patientid,@"start_date":self.startDate,@"end_date":self.endDate} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if (code == 200) {
            self.dataArray = returnData;
            [self.tableView reloadData];
        }
        if (self.dataArray.count == 0) {
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if (self.dataArray.count == 0) {
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:0];
        }
    }];
}

//查看数据汇总统计图
-(void)checkChartDataAction{
    LGBreathRecordChartController *controller = [[LGBreathRecordChartController alloc]init];
    controller.patientid = self.patientid;
    [self.navigationController pushViewController:controller animated:YES];
}

//选择日期
-(void)selectDateAction:(UIButton *)sender{
    NSInteger index = sender.tag - 1000;
    DatePickerTwoView *pickerView = [[DatePickerTwoView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.title = (index == 0)?@"开始时间":@"结束时间";
    if (index == 0) {
        pickerView.currentDate = self.startDate;
    }else{
        pickerView.currentDate = self.endDate;
    }
    pickerView.index = index;
    pickerView.delegate = self;
    [LGKeyWindow addSubview:pickerView];
}

-(void)sendSelectDate:(NSString *)date index:(NSInteger)index{
    if (index == 0) {
        self.startDate = date;
        if ([self needRestDate:self.startDate endDate:self.endDate]) {
            self.endDate = @"";
            [TooltipView showMessage:@"请选择结束日期" offset:0];
        }else{
            [self requestData];
        }
    }else{
        self.endDate = date;
        if ([self needRestDate:self.startDate endDate:self.endDate]) {
            self.startDate = @"";
            [TooltipView showMessage:@"请选择开始日期" offset:0];
        }else{
            [self requestData];
        }
    }
}

-(void)setStartDate:(NSString *)startDate{
    _startDate = startDate;
    self.startItem.text = startDate;
}

-(void)setEndDate:(NSString *)endDate{
    _endDate = endDate;
    self.endItem.text = endDate;
}

-(void)initRequestDate{
    NSDate *currentDate = [NSDate date];
    // 获取当前日历（Gregorian 日历）
    NSCalendar *calendar = [NSCalendar currentCalendar];
   
   // 创建日期组件，并设置月份的第一天
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth) fromDate:currentDate];
    components.day = 1; // 设置为 1 号
   
   // 获取本月第一天的日期
    NSDate *firstDay = [calendar dateFromComponents:components];
    self.startDate = [self.formatter stringFromDate:firstDay];
    self.endDate = [self.formatter stringFromDate:currentDate];
}

-(BOOL)needRestDate:(NSString *)start endDate:(NSString *)end{
    NSDate *startDate = [self.formatter dateFromString:start];
    NSDate *endDate = [self.formatter dateFromString:end];
    NSComparisonResult result = [endDate compare:startDate];
    if (result == NSOrderedDescending || result == NSOrderedSame) {
        //end 是未来日期、同一天
        return NO;
    }else{
        return YES;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *tempArray = self.dataArray[section][@"list"];
    return tempArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGBreathRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.type = LGPositionTypeSingle;
    NSArray *tempArray = self.dataArray[indexPath.section][@"list"];
    cell.dataDic = tempArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *tempArray = self.dataArray[indexPath.section][@"list"];
    LGBreathRecordDetailController *controller = [[LGBreathRecordDetailController alloc]init];
    controller.recordDate = LGNSString(self.dataArray[indexPath.section][@"date"]);
    controller.dataDic = tempArray[indexPath.row];
    controller.patientid = self.patientid;
    [self.navigationController pushViewController:controller animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return viewPix(40);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(42))];
    
    UIView *iconView = [[UIView alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(20), 4, viewPix(14))];
    iconView.backgroundColor = [UIColor colorWithString:@"#77D4C6"];
    iconView.cornerRidus = 2;
    [headerView addSubview:iconView];
    
    UILabel *dateLabel = [UILabel lableWithText:LGNSString(self.dataArray[section][@"date"]) colorString:@"#282828" textFont:LGFontWeight(16, UIFontWeightSemibold) textAlignment:NSTextAlignmentLeft lines:1];
    dateLabel.frame = CGRectMake(viewPix(32), kMinY(iconView.frame)-viewPix(4), viewPix(150), viewPix(22));
    [headerView addSubview:dateLabel];
    
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return viewPix(2);
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(2))];
    return footerView;
}

#pragma mark
#pragma mark ====> 创建控件
-(UIButton *)chartBtn{
    if(!_chartBtn){
        _chartBtn = [UIButton buttonWithTitle:@"查看训练汇总数据" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#FFFFFF" frame:CGRectMake(Screen_W-viewPix(16)-160, viewPix(8), 160, 34)];
        [_chartBtn addTarget:self action:@selector(checkChartDataAction) forControlEvents:UIControlEventTouchUpInside];
        CAGradientLayer *layer = [CAGradientLayer layer];
        layer.frame = CGRectMake(0, 0, 160, 34);
        layer.startPoint = CGPointMake(0.42, 0.33);
        layer.endPoint = CGPointMake(0.59, 0.6);
        layer.colors = @[(__bridge id)[UIColor colorWithString:@"#8ECFFF"].CGColor, (__bridge id)[UIColor colorWithString:@"#5E8EF5"].CGColor];
        layer.locations = @[@(0), @(1.0f)];
        layer.shadowColor = [UIColor colorWithString:@"#5E8EF5" alpha:0.5].CGColor;
        layer.shadowOffset = CGSizeMake(0, 1);
        layer.shadowRadius = 6;
        [_chartBtn.layer addSublayer:layer];
        _chartBtn.cornerRidus = 17;
        [_chartBtn bringSubviewToFront:_chartBtn.titleLabel];
    }
    return _chartBtn;
}

-(UITextField *)startItem{
    if(!_startItem){
        _startItem = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(53), (Screen_W-viewPix(44))/2.0, viewPix(34))];
        _startItem.tintColor = [UIColor colorWithString:@"#333333"];
        _startItem.textColor = [UIColor colorWithString:@"#333333"];
        _startItem.backgroundColor = [UIColor whiteColor];
        _startItem.textAlignment = NSTextAlignmentLeft;
        _startItem.keyboardType = UIKeyboardTypeDefault;
        _startItem.placeholder = @"请选择开始日期";
        _startItem.cornerRidus = 10;
        _startItem.font = LGFont(14);
        _startItem.leftViewMode = UITextFieldViewModeAlways;
        _startItem.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewPix(12), viewPix(34))];
        _startItem.rightViewMode = UITextFieldViewModeAlways;
        _startItem.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewPix(30), viewPix(34))];
        UIButton *actionBtn = [UIButton buttonWithImage:@"grayTipDown16" frame:CGRectMake(0, 0, (Screen_W-viewPix(44))/2.0, viewPix(34))];
        actionBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        actionBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, viewPix(12));
        actionBtn.tag = 1000;
        [actionBtn addTarget:self action:@selector(selectDateAction:) forControlEvents:UIControlEventTouchUpInside];
        [_startItem addSubview:actionBtn];
    }
    return _startItem;
}

-(UITextField *)endItem{
    if(!_endItem){
        _endItem = [[UITextField alloc]initWithFrame:CGRectMake(kMaxX(self.startItem.frame)+viewPix(12), viewPix(53), (Screen_W-viewPix(44))/2.0, viewPix(34))];
        _endItem.tintColor = [UIColor colorWithString:@"#333333"];
        _endItem.textColor = [UIColor colorWithString:@"#333333"];
        _endItem.backgroundColor = [UIColor whiteColor];
        _endItem.textAlignment = NSTextAlignmentLeft;
        _endItem.keyboardType = UIKeyboardTypeDefault;
        _endItem.placeholder = @"请选择结束日期";
        _endItem.cornerRidus = 10;
        _endItem.font = LGFont(14);
        _endItem.leftViewMode = UITextFieldViewModeAlways;
        _endItem.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewPix(12), viewPix(34))];
        _endItem.rightViewMode = UITextFieldViewModeAlways;
        _endItem.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewPix(30), viewPix(34))];
        UIButton *actionBtn = [UIButton buttonWithImage:@"grayTipDown16" frame:CGRectMake(0, 0, (Screen_W-viewPix(44))/2.0, viewPix(34))];
        actionBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        actionBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, viewPix(12));
        actionBtn.tag = 1001;
        [actionBtn addTarget:self action:@selector(selectDateAction:) forControlEvents:UIControlEventTouchUpInside];
        [_endItem addSubview:actionBtn];
    }
    return _endItem;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, viewPix(100), Screen_W, Screen_H-topBarHeight-viewPix(100)) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGBreathRecordCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

-(NSDateFormatter *)formatter{
    if(!_formatter){
        _formatter = [[NSDateFormatter alloc]init];
        _formatter.dateFormat = @"yyyy-MM-dd";
    }
    return _formatter;
}


@end
